/**
 * @param {string} s
 * @return {number}
 */
var myAtoi = function(s) {
  if(s == "")
    return 0;
  let negative = false, start = false, num = "";
  function isNumber(char) {
    return char <= '9' && char >= '0';
  }
  for(let i = 0; i < s.length; i++) {
    if(!start) {
      if(s[i] == '-') {
        negative = true;
        start = true;
        continue;
      } else if(isNumber(s[i])) {
        num += s[i];
        start = true;
        continue;
      } else if(s[i] == '+') {
        start = true;
        continue;
      } else if(s[i] != " " && s[i] != "+") {
        return 0;
      }
    }
    if(start) {
      if(isNumber(s[i]))
        num += s[i];
      else
        break;
    }
  }
  if(num == "")
    return 0;
  if(negative)
    num = -num;
  if(num <= -(2 ** 31))
    return -(2 ** 31);
  if(num >= (2 ** 31 - 1))
    return (2 ** 31 - 1);
  return parseInt(num);
};

let s = "42";
console.log(myAtoi(s));
s = "   -42";
console.log(myAtoi(s));
s = "4193 with words";
console.log(myAtoi(s));
s = "words and 987";
console.log(myAtoi(s));
s = "-91283472332";
console.log(myAtoi(s));
s = "+-12";
console.log(myAtoi(s));
s = "  0000000000012345678";
console.log(myAtoi(s));
s = "00000-42a1234";
console.log(myAtoi(s));
